"""
图书阅读位置管理路由
提供用户阅读位置的更新和查询功能
"""

from typing import Optional
from fastapi import APIRouter, Header, Query, Body
from fastapi.responses import JSONResponse
from utils.password_utils import get_user_id_from_jwt
from db.operations import UserReadingPositionsOperations
from model.message_model import Message
from model.reading_positions_model import (
    ReadingPosition,
    ReadingPositionResponse,
    ReadingPositionUpdateRequest,
)

# 创建阅读位置相关的子路由
router = APIRouter(
    prefix="/reading-positions",
    tags=["reading-positions"],
    responses={404: {"description": "Not found"}},
)


@router.get("/", summary="阅读位置管理接口信息")
async def get_reading_positions_info():
    """获取阅读位置管理接口信息和使用示例"""
    api_info = {
        "message": "阅读位置管理API接口",
        "endpoints": {
            "GET /api/reading-positions/": "获取阅读位置管理接口信息",
            "POST /api/reading-positions/update": "更新用户图书阅读位置",
            "GET /api/reading-positions/get": "获取用户指定图书的阅读位置",
        },
        "examples": {
            "更新阅读位置": {
                "url": "/api/reading-positions/update",
                "method": "POST",
                "header": "Bearer token",
                "body": {"book_id": 123, "position": 150},
                "description": "更新图书ID为123的阅读位置为第150页",
            },
            "获取阅读位置": {
                "url": "/api/reading-positions/get?book_id=123",
                "method": "GET",
                "header": "Bearer token",
                "description": "获取图书ID为123的阅读位置",
            },
        },
    }
    return JSONResponse(status_code=200, content=api_info)


@router.post("/update", summary="更新用户图书阅读位置")
async def update_reading_position(
    request: ReadingPositionUpdateRequest = Body(..., description="更新阅读位置请求"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """更新用户图书阅读位置"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        # 更新阅读位置的逻辑
        reading_positions_ops = UserReadingPositionsOperations()

        # 准备数据
        reading_data = ReadingPosition(
            user_id=user_id,
            book_id=request.book_id,
            position=request.position,
        ).model_dump()

        result = await reading_positions_ops.batch_upsert_reading_positions(
            [reading_data]
        )

        if result == 0:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="阅读位置更新失败",
                ).model_dump(),
            )

        return JSONResponse(
            status_code=200,
            content=Message(
                message="阅读位置更新成功",
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"更新阅读位置失败: {str(e)}",
            ).model_dump(),
        )


@router.get("/get", summary="获取用户指定图书的阅读位置")
async def get_reading_position(
    book_id: int = Query(..., description="图书ID"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """获取用户指定图书的阅读位置"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        # 获取阅读位置的逻辑
        reading_positions_ops = UserReadingPositionsOperations()

        user_book_id = {"user_id": user_id, "book_id": book_id}

        reading_position = await reading_positions_ops.batch_query_reading_positions(
            user_book_ids=[user_book_id]
        )

        if not reading_position:
            return JSONResponse(
                status_code=404,
                content=ReadingPositionResponse(
                    message="未找到阅读位置",
                    reading_positions_data=ReadingPosition(
                        user_id=user_id,
                        book_id=book_id,
                        position=0,
                    ),
                ).model_dump(),
            )

        reading_position_data = reading_position[0]
        return JSONResponse(
            status_code=200,
            content=ReadingPositionResponse(
                message="获取阅读位置成功",
                reading_positions_data=ReadingPosition(**reading_position_data),
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"获取阅读位置失败: {str(e)}",
            ).model_dump(),
        )
